package com.gitee.huanminabc.jnetty.websocket;

import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import com.gitee.huanminabc.jnetty.server.NettyServer;

import java.util.function.Consumer;
@Slf4j
@Data
public class NettyWebSocketServer {
   private NettyServer  nettyServer;

    public NettyWebSocketServer(Integer port, Consumer<ChannelPipeline> consumer) {
        NettyServer nettyServer =new  NettyServer(port, (p)->{
            //对http协议的支持.
            p.addLast(new HttpServerCodec());
            // 对大数据流的支持
            p.addLast(new ChunkedWriteHandler());
            // post请求分三部分. request line / request header / message body ,如果只是单纯的用HttpServerCodec是无法完全的解析Http POST请求的
            p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
            // 将http协议升级为ws协议. websocket的支持
            p.addLast(new WebSocketServerProtocolHandler("/channel",null,false,Integer.MAX_VALUE));
            consumer.accept(p);
        });
        this.nettyServer=nettyServer;
        new Thread(nettyServer::startSync).start();
    }

}
